<template>
	<view class="auth-wrap" v-if="isAuth != null">
		<view class="auth-audit" v-if="isAuth == 0">
			<image src="http://k8s.vendingtech.vip/images/auth_warn@2x.png" class="pic2"></image>
			<view class="txt1">认证审核中</view>
			<view class="info1">我们会在1-2个工作日内给予审核结果，请耐心等待</view>
		</view>

		<view class="auth-audit" v-if="isAuth == 2">
			<image src="http://k8s.vendingtech.vip/images/auth_warn@2x.png" class="pic2"></image>
			<view class="txt1">医生认证被驳回</view>
			<view class="info1" v-if="formData.opinion">{{ formData.opinion }}</view>
		</view>

		<view class="auth-audit" v-if="isAuth == 1">
			<image src="http://k8s.vendingtech.vip/images/auth_success@2x.png" class="pic2"></image>
			<view class="txt1">医生认证成功</view>
		</view>
		<uni-forms label-width="100" :rules="rules" :value="formData" ref="form" err-show-type="toast">
			<view class="auth-box1">
				<view class="auth-title">
					<u-title value="请如实填写您的真实信息"></u-title>
				</view>
				<uni-forms-item label="邀请码" name="parentUserId">
					<view class="item-right">
						<view v-if="!formData.parentUserId" class="item-right-select">无</view>
						<view v-if="formData.parentUserId" class="item-right-value">{{ formData.parentUserId }}</view>
					</view>
				</uni-forms-item>

				<uni-forms-item label="真实姓名" name="doctorName" required>
					<uni-easyinput @input="checkDisabledBtn" :maxlength="20" type="text" v-model="formData.doctorName"
						placeholder="请输入姓名" />
				</uni-forms-item>

				<uni-forms-item label="身份证" name="doctorName" required>
					<uni-easyinput @input="checkDisabledBtn" :maxlength="30" type="text" v-model="formData.idNum"
						placeholder="请输入居民身份证号" />
				</uni-forms-item>

				<uni-forms-item label="性别" required name="sex">
					<uni-data-checkbox :value="formData.sex" :localdata="rangeSex" @change="sexChange">
					</uni-data-checkbox>
				</uni-forms-item>

				<uni-forms-item label="联系方式" name="phone" required>
					<uni-easyinput @input="checkDisabledBtn" :maxlength="20" type="number" v-model="formData.phone"
						placeholder="请输入联系方式" />
				</uni-forms-item>

				<uni-forms-item label="验证码" name="regCode" required>
					<view class="regCode">
						<uni-easyinput style="flex: 1" @input="checkDisabledBtn" :maxlength="20" type="number"
							v-model="formData.regCode" placeholder="请输入验证码" />
						<button v-if="!verifydate" @click="phoneValidate">获取验证码</button>
						<button v-else style="background: #ACB1C2;">
							{{ verifydate }}s后重新获取</button>
					</view>
				</uni-forms-item>

				<uni-forms-item label="就职医院" name="hospId" required>
					<picker mode="selector" :range="hospitalList" range-key="hospName" @change="hospitalChange"
						:value="hosptalIndex">
						<view class="item-right">
							<view v-if="!formData.hospId" class="item-right-select">请选择您目前所执业的医院</view>
							<image v-if="!formData.hospId" class="item-right-next"
								src="http://k8s.vendingtech.vip/images/next_icon@2x.png"></image>
							<view v-if="formData.hospId" class="item-right-value">{{ hospitalList[hosptalIndex].hospName
							}}</view>
						</view>
					</picker>
				</uni-forms-item>

				<uni-forms-item label="所属科室" name="sicknessDepartmentId" required>
					<picker mode="selector" :range="ksList" range-key="departmentName" @change="ksChange"
						:value="ksIndex">
						<view class="item-right">
							<view v-if="!formData.sicknessDepartmentId" class="item-right-select">请选择您所属的科室</view>
							<image v-if="!formData.sicknessDepartmentId" class="item-right-next"
								src="http://k8s.vendingtech.vip/images/next_icon@2x.png"></image>
							<view v-if="formData.sicknessDepartmentId" class="item-right-value">{{
									ksList[ksIndex].departmentName
							}}</view>
						</view>
					</picker>
				</uni-forms-item>

				<uni-forms-item label="职称" name="jobGrade" required>
					<picker mode="selector" :range="jobGradeConfig" @change="jobGradeChange" :value="formData.jobGrade">
						<view class="item-right">
							<view v-if="formData.jobGrade == null" class="item-right-select">请选择您目前的职称</view>
							<image v-if="formData.jobGrade == null" class="item-right-next"
								src="http://k8s.vendingtech.vip/images/next_icon@2x.png"></image>
							<view v-if="formData.jobGrade != null" class="item-right-value">{{
									jobGradeConfig[formData.jobGrade]
							}}</view>
						</view>
					</picker>
				</uni-forms-item>

				<uni-forms-item label="资格证编号" name="certificateCode" required>
					<uni-easyinput @input="checkDisabledBtn" :maxlength="50" type="number" v-model="formData.certificateCode"
						placeholder="请输入资格证编号" />
				</uni-forms-item>

				<uni-forms-item label="执业起始时间" name="docDateStart" class="doc-date" required>
					<view class="item-right">
						<uni-datetime-picker type="date" v-model="formData.docDateStart" :clear-icon="false" :border="false">
							<view v-if="formData.docDateStart" class="uni-input">{{formData.docDateStart}}</view>
							<view v-else class="item-right-select">请选择执业起始时间</view>
						</uni-datetime-picker>
						<image v-if="!formData.docDateStart" class="item-right-next"
							src="http://k8s.vendingtech.vip/images/next_icon@2x.png"></image>
					</view>
				</uni-forms-item>

				<uni-forms-item label="执业终止时间" name="docDateEnd" class="doc-date" required>
					<view class="item-right">
						<uni-datetime-picker type="date" v-model="formData.docDateEnd" :clear-icon="false" :border="false">
							<view v-if="formData.docDateEnd" class="uni-input">{{formData.docDateEnd}}</view>
							<view v-else class="item-right-select">请选择执业终止时间</view>
						</uni-datetime-picker>
						<image v-if="!formData.docDateEnd" class="item-right-next"
							src="http://k8s.vendingtech.vip/images/next_icon@2x.png"></image>
					</view>
				</uni-forms-item>

				<uni-forms-item :borderBottom="false" label="擅长领域" name="goodsDirection" required></uni-forms-item>
				<textarea placeholder-class="textarea-place" :maxlength="1000" class="textarea-box"
					v-model="formData.goodsDirection" @input="checkDisabledBtn"
					placeholder="填写示例：关节疾病，常见关节炎，关节疼痛诊治。骨折，对创伤疾病有大量治疗经验" />
				<uni-forms-item :borderBottom="false" label="个人简介" name="intro" required></uni-forms-item>
				<textarea placeholder-class="textarea-place" :maxlength="1000" class="textarea-box"
					v-model="formData.intro" @input="checkDisabledBtn"
					placeholder="填写示例：医学博士。毕业于北京大学八年制本博连读专业。国际脊柱内固定学会（AOSpine）会员。主要擅长脊柱外科微创手术治疗。" />
			</view>

			<view class="auth-box2">
				<u-title value="医生头像"></u-title>
				<uni-forms-item v-show="false" name="pictures"></uni-forms-item>
				<uni-forms-item v-show="false" name="idPictures"></uni-forms-item>
				<uni-forms-item v-show="false" name="certificates"></uni-forms-item>
				<u-upload-image v-if="applyShow" :file-list="formData.pictures" :limit="1"
					@on-success="uploadSuccess($event, 'pictures')" @on-error="uploadError($event, 'pictures')"
					@on-remove="uploadRemove($event, 'pictures')" />
				<u-title value="身份证件（正反面均需上传）"></u-title>
				<u-upload-image v-if="applyShow" :file-list="formData.idPictures" :limit="2"
					@on-success="uploadSuccess($event, 'idPictures')" @on-error="uploadError($event, 'idPictures')"
					@on-remove="uploadRemove($event, 'idPictures')" />
				<u-title value="胸牌/执业证/资格证/职称证，至少上传一项"></u-title>
				<u-upload-image v-if="applyShow" :file-list="formData.certificates" :limit="4"
					@on-success="uploadSuccess($event, 'certificates')" @on-error="uploadError($event, 'certificates')"
					@on-remove="uploadRemove($event, 'certificates')" />
				<view class="auth-box2-tip">该页所有均为必填项，照片仅用作认证，平台会保护您的隐私，不会泄漏给第三方！</view>
			</view>
			<view style="display: flex;align-items: center;margin: 24rpx auto 0;justify-content: center;">
				<view class="checkbox_wrap" @click="handleCheck">
					<view class="checkbox_circle">
						<view v-if="hasRead"></view>
					</view>
				</view>
				<text class="agree-black">我已阅读并同意</text>
				<text class="agree-color" @click="ilgin_on()">《{{ protocol.title }}》</text>
			</view>
		</uni-forms>
		<u-bottom-button v-if="isAuth == 3" value="提交认证" :disabled="disabled" @click="formSubmit(0)"></u-bottom-button>
		<u-bottom-button v-if="isAuth != 3" value="修改认证" :disabled="disabled" @click="formSubmit(1)"></u-bottom-button>
		<u-loginagreement ref="login_agr" :tatle="protocol.title" :content="protocol.content"></u-loginagreement>
	</view>
</template>

<script>
import uTitle from '@/components/u-title/u-title.vue';
import uBottomButton from '@/components/u-bottom-button/u-bottom-button.vue';
import uniEasyinput from '@/components/uni/uni-easyinput/uni-easyinput.vue';
import uniForms from '@/components/uni/uni-forms/uni-forms.vue';
import uniFormsItem from '@/components/uni/uni-forms-item/uni-forms-item.vue';
import uUploadImage from '@//components/u-upload-image/u-upload-image.vue';
import uniDataCheckbox from '@/components/uni/uni-data-checkbox/uni-data-checkbox.vue';
import ULoginagreement from '@/components/u-loginagreement/u-loginagreement.vue';
import uniDatetimePicker from '@/components/uni/uni-datetime-picker/uni-datetime-picker.vue';
export default {
	components: {
		uniDataCheckbox,
		uBottomButton,
		uTitle,
		uniForms,
		uniFormsItem,
		uniEasyinput,
		uUploadImage,
		ULoginagreement,
		uniDatetimePicker
	},
	data() {
		return {
			rules: {
				doctorName: {
					rules: [
						{
							required: true,
							errorMessage: '请填写姓名'
						}
					]
				},
				idNum: {
					rules: [
						{
							required: true,
							errorMessage: '请填写身份证号'
						}
					]
				},
				sex: {
					rules: [
						{
							required: true,
							errorMessage: '请选择性别'
						}
					]
				},

				phone: {
					rules: [
						{
							required: true,
							errorMessage: '请填写手机号码'
						},
						{
							pattern: '^1[3456789]\\d{9}$',
							errorMessage: '请填写正确的手机号格式'
						}
					]
				},
				regCode: {
					rules: [
						{
							required: true,
							errorMessage: '请填写验证码'
						}
					]
				},

				hospId: {
					rules: [
						{
							required: true,
							errorMessage: '请选择就职医院'
						}
					]
				},

				sicknessDepartmentId: {
					rules: [
						{
							required: true,
							errorMessage: '请选择所属科室'
						}
					]
				},

				jobGrade: {
					rules: [
						{
							required: true,
							errorMessage: '请选择职称'
						}
					]
				},

				goodsDirection: {
					rules: [
						{
							required: true,
							errorMessage: '请填写擅长领域'
						}
					]
				},

				intro: {
					rules: [
						{
							required: true,
							errorMessage: '请填写个人简介'
						}
					]
				},

				pictures: {
					rules: [
						{
							type: 'array',
							required: true,
							errorMessage: '请上传医生头像'
						}
					]
				},

				idPictures: {
					rules: [
						{
							type: 'array',
							required: true,
							errorMessage: '请上传身份证件'
						},
						{
							type: 'array',
							minLength: 2,
							errorMessage: '身份证件需上传正反面'
						}
					]
				},

				certificates: {
					rules: [
						{
							type: 'array',
							required: true,
							errorMessage: '请上传胸牌/执业证/资格证/职称证'
						}
					]
				}
			},
			hasRead: false, //协议阅读
			applyShow: true,
			disabled: true,
			verifydate: '',  //验证码缓冲时间
			isAuth: null, //认证信息  0 审核中 1已审核 2已驳回 3未提交
			ksList: [],
			hospitalList: [],
			hosptalIndex: null, //选择医院下标
			ksIndex: null, //选择科室下标
			formData: {
				parentUserId: '',
				certificates: [], //职业证明
				doctorName: '', //医生姓名
				idNum: '',  //身份证号
				doctorType: 1, //医生类型  1医生  2药师
				goodsDirection: '', //擅长方向
				hospId: null, //医院id
				idPictures: [], //身份证件
				intro: '', //简介
				sex: 0, //性别
				jobGrade: null, //职称 1'医师', 2'医士', 3'住院医师', 4'主治医师', 5'副主任医师', 6'主任医师', 7'药士', 8'药师', 9'主管药师', 10'副主任药师', 11'主任药师'
				phone: '', //联系方式
				regCode: '', //验证码
				pictures: [], //照片
				sicknessDepartmentId: null, //科室id
				certificateCode: null, // 资格证编号
				docDateStart: null, // 执业起始时间
				docDateEnd: null, // 执业终止时间
			},
			protocol: {} //协议
		};
	},
	onLoad(option) {
		// 获取缓存的机构父id
		this.formData.parentUserId = getApp().globalData.parentDoctorId || '';
		this.formData.doctorType = option.doctorType ? option.doctorType : 1;
		if (this.formData.doctorType == 1) {
			uni.setNavigationBarTitle({
				title: '医生认证'
			})
		} else {
			uni.setNavigationBarTitle({
				title: '药师认证'
			})
		}
		this.queryHospList();
	},
	onShow() {
		this.getProtocol()
	},
	computed: {
		pictureJoin() {
			return this.formData.pictures.join(',');
		},
		idPictureJoin() {
			return this.formData.idPictures.join(',');
		},
		certificateJoin() {
			return this.formData.certificates.join(',');
		},

		pictureSplit() {
			return this.formData.picture ? this.formData.picture.split(',') : [];
		},
		idPictureSplit() {
			return this.formData.idPicture ? this.formData.idPicture.split(',') : [];
		},
		certificateSplit() {
			return this.formData.certificate ? this.formData.certificate.split(',') : [];
		}
	},
	methods: {
		getDate(type) {
			const date = new Date()
			let year = date.getFullYear()
			let month = date.getMonth() + 1
			let day = date.getDate()

			if (type === 'start') {
					year = year - 60
			} else if (type === 'end') {
					year = year + 2
			}
			month = month > 9 ? month : '0' + month
			day = day > 9 ? day : '0' + day
			return `${year}-${month}-${day}`
		},
		bindDocStartDateChange(e) {
            this.formData.docDateStart = e.detail.value
        },
		bindDocEndDateChange(e) {
            this.formData.docDateEnd = e.detail.value
        },
		ilgin_on() {
			this.$refs.login_agr.login_on()
		},
		// 获取协议
		getProtocol() {
			let type = this.formData.doctorType == 1 ? 'doctor' : 'senior'
			this.$api.getProtocol({ type: type }).then(e => {
				const { code, result } = e
				if (code == 200) {
					this.protocol = result
				} else {
					uni.showToast({
						title: res.message,
						icon: 'none'
					});
				}
			})
		},
		//校验表单
		formSubmit(type) {
			this.$refs.form
				.submit()
				.then(res => {
					if (type == 0) {
						this.commitDoctorAuth();
					} else {
						this.updateDoctor();
					}
				})
				.catch(err => {
					console.log('表单错误信息：', err);
				});
		},

		//校验按钮
		checkDisabledBtn() {
			let b = false;
			Object.keys(this.formData).forEach(key => {
				if (this.formData[key] === '' || this.formData[key] === null || (typeof this.formData[key] == 'object' && this.formData[key].length == 0)) {
					if (key != 'opinion' && key != 'parentUserId') {
						b = true;
					}
				}
			});
			if (!this.hasRead) {
				b = true
			}
			this.disabled = b;
		},

		//科室列表
		queryKsList() {
			this.$api.queryKsList({}).then(res => {
				if (res.code == 200) {
					this.ksList = res.result;
					this.findAuthDoctroInfo();
				} else {
					uni.showToast({
						title: res.message,
						icon: 'none'
					});
				}
			});
		},

		//医院列表
		queryHospList() {
			this.$api
				.queryHospList({
					params: {
						pageNo: 1,
						pageSize: 9999
					}
				})
				.then(res => {
					if (res.code == 200) {
						this.hospitalList = res.result.records;
						this.queryKsList();
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none'
						});
					}
				});
		},

		//认证信息查询
		findAuthDoctroInfo() {
			this.$api
				.findAuthDoctroInfo({
					params: {
						doctorType: this.formData.doctorType
					}
				})
				.then(res => {
					if (res.code == 200) {
						this.formData = res.result;
						this.formData.parentUserId = getApp().globalData.parentDoctorId || '';
						this.formData.pictures = this.pictureSplit;
						this.formData.idPictures = this.idPictureSplit;
						this.formData.certificates = this.certificateSplit;
						this.hosptalIndex = this.getIndex('hospitalList', this.formData.hospId);
						this.ksIndex = this.getIndex('ksList', this.formData.sicknessDepartmentId);
						this.isAuth = this.formData.checkStatus;
						this.checkDisabledBtn();
					} else {
						this.isAuth = 3;
					}
				});
		},

		//首次提交认证资料
		commitDoctorAuth() {
			this.formData.picture = this.pictureJoin;
			this.formData.idPicture = this.idPictureJoin;
			this.formData.certificate = this.certificateJoin;
			this.$api
				.commitDoctorAuth({
					data: this.formData
				})
				.then(res => {
					uni.showToast({
						title: res.message,
						icon: 'none'
					});
					if (res.code == 200) {
						this.findAuthDoctroInfo();
						uni.pageScrollTo({
							scrollTop: 0,
							duration: 300
						});
					}
				});
		},

		//修改医师认证资料
		updateDoctor() {
			this.$api
				.updateDoctor({
					data: this.formData
				})
				.then(res => {
					uni.showToast({
						title: res.message,
						icon: 'none'
					});
					if (res.code == 200) {
						this.findAuthDoctroInfo();
						uni.pageScrollTo({
							scrollTop: 0,
							duration: 300
						});
					}
				});
		},

		uploadSuccess(res, index) {
			if (res.code == 200) {
				this.formData[index].push(res.result.url);
				this.applyShow = false;
				this.applyShow = true;
			} else {
				uni.showToast({
					title: '文件上传失败',
					icon: 'none'
				});
			}
			this.checkDisabledBtn();
		},
		uploadError(e, index) {
			uni.showToast({
				title: '文件上传失败',
				icon: 'none'
			});
			this.checkDisabledBtn();
		},
		uploadRemove(e, index) {
			this.formData[index].splice(e, 1);
			this.applyShow = false;
			this.applyShow = true;
			this.checkDisabledBtn();
		},

		//性别修改
		sexChange(e) {
			this.formData.sex = e.detail.value;
			this.checkDisabledBtn();
		},

		//科室修改
		ksChange(e) {
			this.ksIndex = e.detail.value;
			this.formData.sicknessDepartmentId = this.ksList[this.ksIndex].id;
			this.checkDisabledBtn();
		},

		//医院修改
		hospitalChange(e) {
			this.hosptalIndex = e.detail.value;
			this.formData.hospId = this.hospitalList[this.hosptalIndex].id;
			this.checkDisabledBtn();
		},

		//获取下标
		getIndex(list, id) {
			let index;
			this[list].forEach((res, key) => {
				if (res.id == id) {
					index = key;
				}
			});
			return index;
		},

		//职称修改
		jobGradeChange(e) {
			this.formData.jobGrade = parseInt(e.detail.value);
			this.checkDisabledBtn();
		},

		// 发送验证码
		phoneValidate() {
			if (this.formData.phone) {
				const data = {
					phone: this.formData.phone,
					type: '2'
				}

				if (this.formData.doctorType == 1) {
					data.type = '2'
				} else if (this.formData.doctorType == 2) {
					data.type = '3'
				}
				this.$api.phoneValidate({
					data: data
				}).then(e => {
					this.verifydate = 30
					const setIid = setInterval(() => {
						if (this.verifydate <= 0) {
							clearInterval(setIid)
						} else {
							this.verifydate--;
						}
					}, 1000)
					if (e.code != 200) {
						uni.showToast({
							title: e.message,
							icon: 'none'
						});
					}
				})
			} else {
				uni.showToast({
					title: '手机号不能为空',
					icon: 'none'
				});
			}

		},

		handleCheck() {
			this.hasRead = !this.hasRead;
			this.checkDisabledBtn()
		},
	}
};
</script>

<style lang="less">
@import './auth.less';
</style>
